package topic.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.foamtrace.photopicker.ImageCaptureManager;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import topic.adapter.DeliverCommentGridViewAdapter;
import topic.bean.DeliverCommentPictureBean;
import utils.BitmapUtils;
import utils.KeyBoard;
import utils.MyLogUtils;
import utils.ToastUtils;
import view.MyGridView;

/**
 * Created by Administrator on 2017/3/13.
 * 发表帖子
 */
@ContentView(R.layout.deliver_blog)
public class DeliverBlog extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.deliver_comment_back)
    private ImageView deliver_comment_back;
    @ViewInject(R.id.deliver_comment_picture)
    private ImageView deliver_comment_picture;
    @ViewInject(R.id.deliver_comment_finish)
    private TextView deliver_comment_finish;
    @ViewInject(R.id.deliver_comment_number)
    private TextView deliver_comment_number;
    @ViewInject(R.id.deliver_comment_content)
    private EditText deliver_comment_content;
    @ViewInject(R.id.deliver_comment_gridView)
    private MyGridView deliver_comment_gridView;
    private String content;//输入的内容
    private String collegeid;
    private String topicid;
    private int hasUploadCount;//已经上传的图片

    private DeliverCommentGridViewAdapter deliverCommentGridViewAdapter;
    private ArrayList<DeliverCommentPictureBean> photoPaths = new ArrayList<>();//图片路径
    private ArrayList<String> photoPaths1 = new ArrayList<>();//图片路径,用于进入多选框用的
    private ImageCaptureManager captureManager;
    private final int REQUEST_CAMERA_CODE = 0;
    private final int REQUEST_PREVIEW_CODE = 2;
    private boolean hasDeliver = false;//每次只能发一条博客
    private static final String TAG = "DeliverBlog";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    setResult(Constant.ERROR_CODE_SUCCESS);
                    hasDeliver = false;
                    DeliverBlog.this.finish();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        collegeid = getIntent().getStringExtra("id");
        topicid = getIntent().getStringExtra("topicid");
        initView();
        KeyBoard.showKeyBoard();
    }

    private void initView() {
        deliver_comment_back.setOnClickListener(this);
        deliver_comment_picture.setOnClickListener(this);
        deliver_comment_finish.setOnClickListener(this);
        new Thread(()->MyLogUtils.e(TAG)).start();
        deliver_comment_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 255) {
                    deliver_comment_content.setText(content);
                    deliver_comment_content.setSelection(content.length());
                    ToastUtils.shortToast("输入字数已达上限");
                } else {
                    content = s.toString();
                }
                deliver_comment_number.setText("" + content.length());
            }
        });
        deliverCommentGridViewAdapter = new DeliverCommentGridViewAdapter(DeliverBlog.this, photoPaths, position -> {
            //删除某个图片
            if (hasUploadCount <= 0) {
                photoPaths.remove(position);
                photoPaths1.remove(position);
                deliverCommentGridViewAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.shortToast("图片未上传完");
            }
        }, (position, hasUpload, url) -> {
            photoPaths.get(position).setHasUpLoad(true);
            photoPaths.get(position).setRemoteUrl(url);
            hasUploadCount--;
        }, () -> {
            //读取图片失败
            hasUploadCount--;
        });
        deliver_comment_gridView.setHorizontalSpacing(0);
        deliver_comment_gridView.setVerticalSpacing(5);
        deliver_comment_gridView.setAdapter(deliverCommentGridViewAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.deliver_comment_back:
                DeliverBlog.this.finish();
                break;
            case R.id.deliver_comment_picture:
                PhotoPickerIntent photoPickerIntent = new PhotoPickerIntent(DeliverBlog.this);
                photoPickerIntent.setSelectModel(SelectModel.MULTI);
                photoPickerIntent.setShowCarema(true); // 是否显示拍照， 默认false
                photoPickerIntent.setMaxTotal(9); // 最多选择照片数量，默认为9
                photoPickerIntent.setSelectedPaths(photoPaths1);
                startActivityForResult(photoPickerIntent, REQUEST_CAMERA_CODE);
                break;
            case R.id.deliver_comment_finish:
                MyLogUtils.e(TAG, "photoPaths.size = " + photoPaths.size() + "::::::::hasUploadCount = " + hasUploadCount);
                if (hasUploadCount == 0) {
                    if (!hasDeliver) {
                        commitContent(photoPaths, deliver_comment_content.getText().toString());
                        hasDeliver = true;
                    }
                } else {
                    ToastUtils.shortToast("图片未上传完成");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    refreshAdapter(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        // 照片地址
                        if (photoPaths1.size() < 9) {
                            String imagePath = captureManager.getCurrentPhotoPath();
                            DeliverCommentPictureBean deliverCommentPictureBean = new DeliverCommentPictureBean();
                            deliverCommentPictureBean.setLocalUrl(imagePath);
                            photoPaths.add(deliverCommentPictureBean);
                            photoPaths1.add(imagePath);
                        }
                        deliverCommentGridViewAdapter.notifyDataSetChanged();
                    }
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    refreshAdapter(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
            }
        }
    }

    private void refreshAdapter(final ArrayList<String> paths) {
        // 处理返回照片地址
        final ArrayList<String> arrayList = new ArrayList<>();
        final ArrayList<DeliverCommentPictureBean> arrayList2 = new ArrayList<>();
        if (photoPaths1 != null) {
            for (int i = 0; i < photoPaths1.size(); i++) {
                arrayList.add(photoPaths1.get(i));
                arrayList2.add(photoPaths.get(i));
            }
            photoPaths1.clear();
            photoPaths.clear();
        }
        if (paths != null) {
            for (int i = 0; i < paths.size(); i++) {
                if (BitmapUtils.isBitmapExists(paths.get(i))) {
                    MyLogUtils.e(TAG, paths.get(i));
                    DeliverCommentPictureBean deliverCommentPictureBean = new DeliverCommentPictureBean();
                    if (!arrayList.contains(paths.get(i))) {
                        //当数组中没有这个图片时
                        hasUploadCount++;
                        deliverCommentPictureBean.setHasUpLoad(false);
                    } else {
                        deliverCommentPictureBean.setHasUpLoad(true);
                        deliverCommentPictureBean.setRemoteUrl(arrayList2.get(arrayList.indexOf(paths.get(i))).getRemoteUrl());//将原本的数据迁移过来
                        deliverCommentPictureBean.setName(arrayList2.get(arrayList.indexOf(paths.get(i))).getName());
                        deliverCommentPictureBean.setLocalUrl(arrayList2.get(arrayList.indexOf(paths.get(i))).getLocalUrl());
                    }
                    deliverCommentPictureBean.setLocalUrl(paths.get(i));
                    photoPaths1.add(paths.get(i));
                    photoPaths.add(deliverCommentPictureBean);
                    deliverCommentGridViewAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        collegeid = null;
        topicid = null;
    }

    public void commitContent(ArrayList<DeliverCommentPictureBean> photoPaths, String content) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("content", content);
        if (!TextUtils.isEmpty(collegeid)) {
            hashMap.put("collegeid", collegeid);
        }
        if (!TextUtils.isEmpty(topicid)) {
            hashMap.put("topicid", topicid);
        }
        String images = "";
        String substring = "";
        if (photoPaths != null) {
            if (photoPaths.size() > 0) {
                for (int i = 0; i < photoPaths.size(); i++) {
                    images += photoPaths.get(i).getRemoteUrl() + ",";
                }
            }
            if (images.length() > 0) {
                substring = images.substring(0, images.length() - 1);
            }
        }
        hashMap.put("images", substring);
        new InterNetController(DeliverBlog.this, Constant.PUBLISH, handler, hashMap, 0);
    }
}
